<template>
  <div class="laundry-reports">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>统计报表</h1>
        <p class="description">洗护业务数据分析与统计报表</p>
      </div>
      <div class="header-right">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 概览数据卡片 -->
    <div class="overview-cards">
      <div class="overview-card">
        <div class="card-header">
          <div class="card-icon revenue">
            <el-icon><Money /></el-icon>
          </div>
          <div class="card-title">总收入</div>
        </div>
        <div class="card-content">
          <div class="main-value">¥{{ formatNumber(overviewData.totalRevenue) }}</div>
          <div class="sub-value">
            <span :class="getGrowthClass(overviewData.revenueGrowth)">
              {{ overviewData.revenueGrowth > 0 ? '+' : '' }}{{ overviewData.revenueGrowth }}%
            </span>
            较上期
          </div>
        </div>
      </div>

      <div class="overview-card">
        <div class="card-header">
          <div class="card-icon orders">
            <el-icon><Document /></el-icon>
          </div>
          <div class="card-title">订单总数</div>
        </div>
        <div class="card-content">
          <div class="main-value">{{ formatNumber(overviewData.totalOrders) }}</div>
          <div class="sub-value">
            <span :class="getGrowthClass(overviewData.ordersGrowth)">
              {{ overviewData.ordersGrowth > 0 ? '+' : '' }}{{ overviewData.ordersGrowth }}%
            </span>
            较上期
          </div>
        </div>
      </div>

      <div class="overview-card">
        <div class="card-header">
          <div class="card-icon customers">
            <el-icon><User /></el-icon>
          </div>
          <div class="card-title">客户总数</div>
        </div>
        <div class="card-content">
          <div class="main-value">{{ formatNumber(overviewData.totalCustomers) }}</div>
          <div class="sub-value">
            <span :class="getGrowthClass(overviewData.customersGrowth)">
              {{ overviewData.customersGrowth > 0 ? '+' : '' }}{{ overviewData.customersGrowth }}%
            </span>
            较上期
          </div>
        </div>
      </div>

      <div class="overview-card">
        <div class="card-header">
          <div class="card-icon satisfaction">
            <el-icon><Star /></el-icon>
          </div>
          <div class="card-title">满意度</div>
        </div>
        <div class="card-content">
          <div class="main-value">{{ overviewData.satisfaction }}%</div>
          <div class="sub-value">
            <span :class="getGrowthClass(overviewData.satisfactionGrowth)">
              {{ overviewData.satisfactionGrowth > 0 ? '+' : '' }}{{ overviewData.satisfactionGrowth }}%
            </span>
            较上期
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 收入趋势图 -->
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>收入趋势</h3>
              <el-radio-group v-model="revenueChartType" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
            <div ref="revenueChart" class="chart-container"></div>
          </div>
        </el-col>

        <!-- 订单状态分布 -->
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>订单状态分布</h3>
            </div>
            <div ref="orderStatusChart" class="chart-container"></div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 服务类型销售占比 -->
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>服务类型销售占比</h3>
            </div>
            <div ref="serviceTypeChart" class="chart-container"></div>
          </div>
        </el-col>

        <!-- 设备使用率 -->
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>设备使用率</h3>
            </div>
            <div ref="equipmentChart" class="chart-container"></div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="data-tables">
      <el-row :gutter="20">
        <!-- 热门服务排行 -->
        <el-col :span="12">
          <div class="table-card">
            <div class="table-header">
              <h3>热门服务排行</h3>
            </div>
            <el-table :data="popularServices" style="width: 100%">
              <el-table-column type="index" label="排名" width="60" />
              <el-table-column prop="serviceName" label="服务名称" />
              <el-table-column prop="orderCount" label="订单数" width="80" />
              <el-table-column prop="revenue" label="收入" width="100">
                <template #default="{ row }">
                  ¥{{ formatNumber(row.revenue) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>

        <!-- 客户消费排行 -->
        <el-col :span="12">
          <div class="table-card">
            <div class="table-header">
              <h3>客户消费排行</h3>
            </div>
            <el-table :data="topCustomers" style="width: 100%">
              <el-table-column type="index" label="排名" width="60" />
              <el-table-column prop="customerName" label="客户姓名" />
              <el-table-column prop="orderCount" label="订单数" width="80" />
              <el-table-column prop="totalAmount" label="消费金额" width="100">
                <template #default="{ row }">
                  ¥{{ formatNumber(row.totalAmount) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  Money,
  Document,
  User,
  Star
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getBusinessOverview,
  getRevenueStats,
  getOrderStats,
  getServiceSalesStats,
  getCustomerAnalysis,
  getEquipmentUtilization
} from '@/api/laundry'

// 响应式数据
const dateRange = ref([])
const revenueChartType = ref('day')
const overviewData = ref({
  totalRevenue: 0,
  revenueGrowth: 0,
  totalOrders: 0,
  ordersGrowth: 0,
  totalCustomers: 0,
  customersGrowth: 0,
  satisfaction: 0,
  satisfactionGrowth: 0
})

const popularServices = ref([])
const topCustomers = ref([])

// 图表引用
const revenueChart = ref(null)
const orderStatusChart = ref(null)
const serviceTypeChart = ref(null)
const equipmentChart = ref(null)

// 图表实例
let revenueChartInstance = null
let orderStatusChartInstance = null
let serviceTypeChartInstance = null
let equipmentChartInstance = null

// 方法
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num?.toLocaleString() || '0'
}

const getGrowthClass = (growth) => {
  if (growth > 0) return 'growth-positive'
  if (growth < 0) return 'growth-negative'
  return 'growth-neutral'
}

const handleDateChange = () => {
  refreshData()
}

const loadOverviewData = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }
    const response = await getBusinessOverview(params)
    overviewData.value = response.data || {}
  } catch (error) {
    console.error('Load overview data error:', error)
  }
}

const initRevenueChart = async () => {
  try {
    const params = {
      type: revenueChartType.value,
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }
    const response = await getRevenueStats(params)
    const data = response.data || {}

    const option = {
      title: {
        text: '收入趋势',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          return `${params[0].name}<br/>收入: ¥${params[0].value}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.labels || []
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [
        {
          name: '收入',
          type: 'line',
          smooth: true,
          data: data.values || [],
          lineStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ]
            }
          }
        }
      ]
    }

    if (revenueChartInstance) {
      revenueChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('Init revenue chart error:', error)
  }
}

const initOrderStatusChart = async () => {
  try {
    const response = await getOrderStats({
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    })
    const data = response.data || {}

    const option = {
      title: {
        text: '订单状态分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '订单状态',
          type: 'pie',
          radius: '50%',
          data: data.statusDistribution || [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }

    if (orderStatusChartInstance) {
      orderStatusChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('Init order status chart error:', error)
  }
}

const initServiceTypeChart = async () => {
  try {
    const response = await getServiceSalesStats({
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    })
    const data = response.data || {}

    const option = {
      title: {
        text: '服务类型销售占比',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
      },
      series: [
        {
          name: '销售额',
          type: 'pie',
          radius: ['40%', '70%'],
          data: data.serviceTypes || [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            show: false
          },
          labelLine: {
            show: false
          }
        }
      ]
    }

    if (serviceTypeChartInstance) {
      serviceTypeChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('Init service type chart error:', error)
  }
}

const initEquipmentChart = async () => {
  try {
    const response = await getEquipmentUtilization({
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    })
    const data = response.data || {}

    const option = {
      title: {
        text: '设备使用率',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          return `${params[0].name}<br/>使用率: ${params[0].value}%`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.equipmentNames || []
      },
      yAxis: {
        type: 'value',
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [
        {
          name: '使用率',
          type: 'bar',
          data: data.utilizationRates || [],
          itemStyle: {
            color: (params) => {
              const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']
              return colors[params.dataIndex % colors.length]
            }
          }
        }
      ]
    }

    if (equipmentChartInstance) {
      equipmentChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('Init equipment chart error:', error)
  }
}

const loadTableData = async () => {
  try {
    const [servicesResponse, customersResponse] = await Promise.all([
      getServiceSalesStats({
        type: 'popular',
        limit: 10,
        startDate: dateRange.value?.[0],
        endDate: dateRange.value?.[1]
      }),
      getCustomerAnalysis({
        type: 'top',
        limit: 10,
        startDate: dateRange.value?.[0],
        endDate: dateRange.value?.[1]
      })
    ])

    popularServices.value = servicesResponse.data?.popularServices || []
    topCustomers.value = customersResponse.data?.topCustomers || []
  } catch (error) {
    console.error('Load table data error:', error)
  }
}

const refreshData = async () => {
  try {
    await loadOverviewData()
    await initRevenueChart()
    await initOrderStatusChart()
    await initServiceTypeChart()
    await initEquipmentChart()
    await loadTableData()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
    console.error('Refresh data error:', error)
  }
}

// 监听收入图表类型变化
watch(revenueChartType, () => {
  initRevenueChart()
})

// 初始化图表
onMounted(async () => {
  // 设置默认日期范围（最近30天）
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  dateRange.value = [startDate, endDate]

  await nextTick()

  // 初始化图表实例
  revenueChartInstance = echarts.init(revenueChart.value)
  orderStatusChartInstance = echarts.init(orderStatusChart.value)
  serviceTypeChartInstance = echarts.init(serviceTypeChart.value)
  equipmentChartInstance = echarts.init(equipmentChart.value)

  // 加载数据
  refreshData()

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    revenueChartInstance?.resize()
    orderStatusChartInstance?.resize()
    serviceTypeChartInstance?.resize()
    equipmentChartInstance?.resize()
  })
})
</script>

<style lang="scss" scoped>
.laundry-reports {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .header-left {
      h1 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2937;
      }

      .description {
        margin: 0;
        color: #6b7280;
        font-size: 14px;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }

  .overview-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;

    .overview-card {
      background: white;
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid #e5e7eb;

      .card-header {
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        .card-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          border-radius: 8px;
          margin-right: 12px;

          &.revenue {
            background: linear-gradient(135deg, #8b5cf6, #7c3aed);
            color: white;
          }

          &.orders {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
          }

          &.customers {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
          }

          &.satisfaction {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
          }
        }

        .card-title {
          font-size: 14px;
          color: #6b7280;
          font-weight: 500;
        }
      }

      .card-content {
        .main-value {
          font-size: 28px;
          font-weight: 700;
          color: #1f2937;
          margin-bottom: 8px;
        }

        .sub-value {
          font-size: 12px;
          color: #6b7280;

          .growth-positive {
            color: #059669;
          }

          .growth-negative {
            color: #dc2626;
          }

          .growth-neutral {
            color: #6b7280;
          }
        }
      }
    }
  }

  .charts-section {
    margin-bottom: 30px;

    .chart-card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid #e5e7eb;

      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #1f2937;
        }
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .data-tables {
    .table-card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid #e5e7eb;

      .table-header {
        margin-bottom: 20px;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #1f2937;
        }
      }
    }
  }
}
</style> 